using System;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
using FreeTextBoxControls;
using GURUCORE.Framework.Business;
using GURUCORE.Framework.Business.DTO;
using GURUCORE.Framework.Core.Data;
using GURUCORE.Framework.DataAccess.ORMapping.CriteriaMapping;

namespace GURUCORE.Portal.Core.BasePagelet
{
    public abstract class TranslatePagelet : Pagelet
    {
        protected const string ACTION_CANCEL = "Cancel";
        protected const string ACTION_SAVE = "Save";

        private Button m_btnCancel;
        private Button m_btnDelete;
        private Button m_btnSave;

        private DropDownList m_cboLocale;

        [PageletSessionfulMember] protected DTOBase m_dtoOriginalData;

        [PageletSessionfulMember] protected DTOBase m_dtoTranlationData;

        public TranslatePagelet()
        {
        }

        protected override void OnPageletInit()
        {
            m_btnSave = (Button) FindControl("btnSave");
            m_btnSave.Click += new EventHandler(m_btnSave_Click);
            m_btnSave.CausesValidation = true;

            m_btnCancel = (Button) FindControl("btnCancel");
            m_btnCancel.Click += new EventHandler(m_btnCancel_Click);
            m_btnCancel.CausesValidation = false;

            m_btnDelete = (Button) FindControl("btnDelete");
            if (m_btnDelete != null)
            {
                m_btnDelete.Click += new EventHandler(m_btnDelete_Click);
                m_btnDelete.CausesValidation = false;
            }

            m_cboLocale = (DropDownList) FindControl("cboLocale");
            IDAUService svc = ServiceLocator.Locate<IDAUService, DAUService>();
            svc.ChangeDataSource(CONST.PORTALBUSINESSDLLGUID, "Portal");
            m_cboLocale.DataSource = svc._GetObjects(typeof (LocaleDTO), default(Expression));
            m_cboLocale.DataTextField = LocaleDTO.CODE_FLD;
            m_cboLocale.DataValueField = LocaleDTO.LOCALEID_FLD;
            m_cboLocale.DataBind();

            //m_cboLocale.Items.Add(new ListItem("en-US", "1"));
            //m_cboLocale.Items.Add(new ListItem("vi-VN", "2"));
            //m_cboLocale.Items.Add(new ListItem("jp-JP", "3"));
            m_cboLocale.AutoPostBack = true;
            m_cboLocale.SelectedIndexChanged += new EventHandler(m_cboLocale_SelectedIndexChanged);
        }

        private void m_btnDelete_Click(object sender, EventArgs e)
        {
            DeleteTranslation(GetComboSelectedValue(m_cboLocale));
            m_dtoTranlationData.Empty();
            BindTranslationData(m_dtoTranlationData);
        }

        private void m_cboLocale_SelectedIndexChanged(object sender, EventArgs e)
        {
            //save
            /*if (Page.IsValid)
			{
				DTOBase dtoData = CollectData();
				SaveTranslation(dtoData);
				OnSave();
			}*/

            DTOBase dtoTranlationData = GetTranslation(GetComboSelectedValue(m_cboLocale));
            if (dtoTranlationData != null)
            {
                m_dtoTranlationData = dtoTranlationData;
            }
            else
            {
                m_dtoTranlationData.Empty();
            }
            BindTranslationData(m_dtoTranlationData);
        }

        private void m_btnCancel_Click(object sender, EventArgs e)
        {
            OnCancel();
            Navigate(ACTION_CANCEL);
        }

        private void m_btnSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                DTOBase dtoData = CollectData();
                SaveTranslation(dtoData);
                OnSave();
                Navigate(ACTION_SAVE);
            }
        }


        private DTOBase CollectData()
        {
            string[] arrControlPrefix = new string[2] {"txt", "fil"};

            //automatic collect
            Type tTranslationDTO = m_dtoTranlationData.GetType();
            Type tOriginalDTO = m_dtoOriginalData.GetType();
            PropertyInfo[] arrProp = tTranslationDTO.GetProperties();

            foreach (PropertyInfo oProp in arrProp)
            {
                string sProp = oProp.Name;

                if (sProp == tOriginalDTO.Name.Substring(0, tOriginalDTO.Name.Length - 3) + "ID")
                {
                    PropertyInfo oOriginalIDProp = tOriginalDTO.GetProperty(sProp);
                    oProp.SetValue(m_dtoTranlationData, oOriginalIDProp.GetValue(m_dtoOriginalData, null), null);
                }

                if (sProp == "LocaleID")
                {
                    oProp.SetValue(m_dtoTranlationData, GetComboSelectedValue(m_cboLocale), null);
                }

                foreach (string sPrefix in arrControlPrefix)
                {
                    Control oCtrl = FindControl(sPrefix + sProp);
                    if (oCtrl is TextBox)
                    {
                        //get value as string
                        //((TextBox)oCtrl).Text = oProp.GetValue(p_dtoData, null).ToString();
                        oProp.SetValue(m_dtoTranlationData, ((TextBox) oCtrl).Text, null);
                        break;
                    }
                    else if (oCtrl is FreeTextBox)
                    {
                        oProp.SetValue(m_dtoTranlationData, ((FreeTextBox) oCtrl).Text, null);
                        break;
                    }
                    else if (oCtrl is FileUpload)
                    {
                        //((Image)oCtrl).ImageUrl = this.GetDataLink(string.Empty, oProp.GetValue(p_dtoData, null).ToString(), false);
                        oProp.SetValue(m_dtoTranlationData,
                                       UploadFile(string.Empty, ((FileUpload) oCtrl).PostedFile, 0, false), null);
                        break;
                    }
                    else if (oCtrl is CheckBox)
                    {
                        //((CheckBox)oCtrl).Checked = Convert.ToBoolean(oProp.GetValue(p_dtoData, null));
                        oProp.SetValue(m_dtoTranlationData, ((CheckBox) oCtrl).Checked, null);
                        break;
                    }
                }
            }

            //custom bind
            OnCollectData(ref m_dtoTranlationData);

            return m_dtoTranlationData;
        }


        protected abstract int SaveTranslation(DTOBase p_dtoData);

        protected abstract DTOBase GetTranslation(int p_nLocaleID);

        protected abstract DTOBase GetOriginalData();

        protected virtual int DeleteTranslation(int p_nLocaleID)
        {
            return 0;
        }

        protected override void OnPageletLoad()
        {
            m_dtoOriginalData = GetOriginalData();
            m_dtoTranlationData = GetTranslation(GetComboSelectedValue(m_cboLocale));

            if (m_dtoOriginalData == null)
            {
                //
                return;
            }

            BindOriginalData(m_dtoOriginalData);

            //reflect to get translation type
            if (m_dtoTranlationData == null)
            {
                string sOriginalDataType = m_dtoOriginalData.GetType().FullName;
                string sTranlationDataType = sOriginalDataType.Substring(0, sOriginalDataType.Length - 3) + "Localized" +
                                             "DTO";
                Assembly oAsm = m_dtoOriginalData.GetType().Assembly;
                Type tTranslationType = oAsm.GetType(sTranlationDataType);
                m_dtoTranlationData = (DTOBase) Activator.CreateInstance(tTranslationType);
            }
            else
            {
                BindTranslationData(m_dtoTranlationData);
            }
        }

        private void BindOriginalData(DTOBase p_dtoData)
        {
            //automatic bind
            Type tDTO = p_dtoData.GetType();
            PropertyInfo[] arrProp =
                tDTO.GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance);

            foreach (PropertyInfo oProp in arrProp)
            {
                string sProp = oProp.Name;

                string sPrefix = "lit";

                Control oCtrl = FindControl(sPrefix + sProp);
                if (oCtrl is Literal)
                {
                    //get value as string
                    if (!p_dtoData.IsNull(sProp))
                    {
                        ((Literal) oCtrl).Text = oProp.GetValue(p_dtoData, null).ToString();
                    }
                }
            }

            //custom bind
            OnBindOriginalData(p_dtoData);
        }

        protected virtual void OnBindOriginalData(DTOBase p_dtoData)
        {
        }

        private void BindTranslationData(DTOBase p_dtoData)
        {
            string[] arrControlPrefix = new string[3] {"txt", "img", "chk"};

            if (p_dtoData == null)
            {
                foreach (Control oCtrl in Controls)
                {
                    if (oCtrl is TextBox)
                    {
                        ((TextBox) oCtrl).Text = string.Empty;
                    }
                    else if (oCtrl is FreeTextBox)
                    {
                        ((FreeTextBox) oCtrl).Text = string.Empty;
                    }
                }
            }
            else
            {
                //automatic bind
                Type tDTO = p_dtoData.GetType();
                PropertyInfo[] arrProp =
                    tDTO.GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance);

                foreach (PropertyInfo oProp in arrProp)
                {
                    string sProp = oProp.Name;
                    foreach (string sPrefix in arrControlPrefix)
                    {
                        Control oCtrl = FindControl(sPrefix + sProp);
                        if (oCtrl is TextBox)
                        {
                            //get value as string
                            if (!p_dtoData.IsNull(sProp))
                            {
                                ((TextBox) oCtrl).Text = oProp.GetValue(p_dtoData, null).ToString();
                            }
                            else
                            {
                                ((TextBox) oCtrl).Text = string.Empty;
                            }
                            break;
                        }
                        else if (oCtrl is FreeTextBox)
                        {
                            if (!p_dtoData.IsNull(sProp))
                            {
                                ((FreeTextBox) oCtrl).Text = oProp.GetValue(p_dtoData, null).ToString();
                                break;
                            }
                            else
                            {
                                ((FreeTextBox) oCtrl).Text = string.Empty;
                            }
                        }
                        else if (oCtrl is Image)
                        {
                            ((Image) oCtrl).ImageUrl =
                                GetDataLink(string.Empty, oProp.GetValue(p_dtoData, null).ToString(), false);
                            break;
                        }
                        else if (oCtrl is CheckBox)
                        {
                            ((CheckBox) oCtrl).Checked = Convert.ToBoolean(oProp.GetValue(p_dtoData, null));
                            break;
                        }
                    }
                }
            }

            //custom bind
            OnBindTranslationData(p_dtoData);
        }

        protected virtual void OnBindTranslationData(DTOBase p_dtoData)
        {
        }


        protected virtual void OnSave()
        {
        }

        protected virtual void OnCancel()
        {
        }

        protected virtual void OnCollectData(ref DTOBase p_dtoData)
        {
        }
    }
}